package manager.fileupload.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import manager.fileupload.service.FileUploadService;
import manager.fileupload.vo.UploadConfig;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
@EnableConfigurationProperties(UploadConfig.class)
@Service(value="fileUploadService")
public class FileUploadServiceimpl implements FileUploadService {
    private Log log = LogFactory.getLog(FileUploadService.class);
    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private UploadConfig uploadConfig;

    public String uploadImage(MultipartFile file) {
        // 1、校验文件类型
        String contentType = file.getContentType();
        if (!uploadConfig.getAllowTypes().contains(contentType)) {
            throw new RuntimeException("文件类型不支持");
        }
        try {
            // 3、上传到FastDFS
            // 3.1、获取扩展名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 3.2、上传
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            // 返回路径
            return uploadConfig.getBaseUrl()+":8888/" + storePath.getFullPath();
        } catch (IOException e) {
            log.error("【文件上传】上传文件失败！....{}", e);
            throw new RuntimeException("【文件上传】上传文件失败！" + e.getMessage());
        }
    }

    @Override
    public String uploadImageByStream(File tempFile) throws IOException {
            StorePath storePath=null;
            InputStream inStream = null;
            try {
                inStream = new FileInputStream(tempFile);
                storePath = storageClient.uploadFile(inStream, tempFile.length(), "jpg", null);
                inStream.close();
            } catch (Exception e) {
                try {
                    inStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }finally {
                inStream.close();
            }
            return uploadConfig.getBaseUrl()+":8888/" + storePath.getFullPath();
    }
}
